package cn.t.modules.scheduler.app;

import cn.t.modules.scheduler.common.enums.ScheduleStatus;
import cn.t.modules.scheduler.common.exeptions.BizException;
import cn.t.modules.scheduler.core.SqlProcessor;
import cn.t.modules.scheduler.core.schedule.repository.po.SchedulePo;
import cn.t.modules.timewheel.core.hierarchical.TTaskScheduler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;

/**
 * @author 陶敏麒
 * @date 2024/3/7 9:15
 */
@Service
@Slf4j
public class ScheduleApp {
    @Resource
    private TTaskScheduler taskScheduler;
    @Resource
    private SqlProcessor sqliteProcessor;

    /**
     * 当前正在队列中的任务总数
     */
    public int currentTaskCount() {
        return this.taskScheduler.currentTaskCount();
    }

    public void clearScheduleHistory(long clearTimeTs) {
        this.sqliteProcessor.clearScheduleHistory(clearTimeTs);
    }

    public int cancelSchedule(String scheduleId) {
        // 找到待执行的计划
        var list = this.sqliteProcessor.queryScheduleList(scheduleId, ScheduleStatus.ACCEPTED);
        if (CollectionUtils.isEmpty(list)) {
            // 计划都已经开始执行了
            throw new BizException("计划已经开始执行,无法取消");
        }
        // 取消
        int count = 0;
        for (SchedulePo schedulePo : list) {
            this.sqliteProcessor.updateStatus(schedulePo.getId(), ScheduleStatus.CANCELLED, "已取消", schedulePo.getVersion());
            var execTs = schedulePo.getExecTimeTs();
            // 执行时间在90秒内的,可能需要更新内存
            if (execTs < System.currentTimeMillis() + 90000 && (this.taskScheduler.cancelSchedule(schedulePo.getScheduleId(), schedulePo.getExecTimeTs()))) {
                    count++;
            }
        }
        return count;
    }
}
